package mis510.homefinders;

import org.w3c.dom.*;
import org.xml.sax.*;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import javax.xml.parsers.*;
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Zillow extends AsyncTask<String, Void, ArrayList<String>>
{

	String result;
    private static final DocumentBuilderFactory dbFac;
    private static final DocumentBuilder docBuilder;
    ArrayList<String> info = new ArrayList<String>();
    static
    {
        try
        {
            dbFac = DocumentBuilderFactory.newInstance();
            docBuilder = dbFac.newDocumentBuilder();
        }
        catch(ParserConfigurationException e)
        {
            throw new RuntimeException(e);
        }
    }
    private static final String DEEP_URL = "http://www.zillow.com/webservice/GetDeepSearchResults.htm";
    //private static final String ZESTIMATE_URL = "http://www.zillow.com/webservice/GetZestimate.htm";
    private static final String ZWSID = "X1-ZWz1bhef5il5hn_6o78e";
    //private static final NumberFormat nf = NumberFormat.getCurrencyInstance();
	private static String lastupdatedT = null;
	private static String amountT = null;
	private static String currency_amt = null;
	
	//ProgressDialog dialog;

//    @Override
//    protected void onPreExecute() {
//        dialog = new ProgressDialog(Zillow.this);
//        dialog.setTitle("Calculating...");
//        dialog.setMessage("Please wait...");
//        dialog.setIndeterminate(true);
//        dialog.show();
//    }


    // Returns Zestimate value for address.
	protected ArrayList<String> doInBackground(String...search_address)
    {
		System.out.println("in zillow");
		String[] search_address_bg = search_address;
		System.out.println("search_address: "+search_address_bg[0]);
		StringTokenizer st = new StringTokenizer(search_address_bg[0], ",");
		String street = st.nextToken();
		String city = st.nextToken();
		String state = st.nextToken();
		String cityStateZip = city+" "+state;
		System.out.println("parsed address: "+ street+cityStateZip);
        Document deepDoc;
		try {
			deepDoc = docBuilder.parse(DEEP_URL + 
			                                "?zws-id=" + ZWSID + 
			                                "&address=" + street + 
			                                "&citystatezip=" + cityStateZip
			                                +"&rentzestimate=true");
        /*System.out.println(DEEP_URL + 
                                        "?zws-id=" + ZWSID + 
                                        "&address=" + address + 
                                        "&citystatezip=" + cityStateZip
                                        +"&rentzestimate=true");*/
        Element statuscode = (Element)deepDoc.getElementsByTagName("message").item(0);
        if (statuscode != null)
        {
        	String code = statuscode.getElementsByTagName("code").item(0).getTextContent();
        	if (code.equals("0"))
        	  {
        		String zpid = null;
        		String yearbuiltT = null;
        		String lotsizeT = null;
        		String bathroomsT = null;
        		String bedroomsT = null;
        		String lastsolddateT = null;
        		String reg_name = null;
    			String overview_link = null;
    			String lowest = null;
    			String currency_low = null;
    			String highest = null;
    			String currency_high = null;
    			
        		Element firstResult = (Element)deepDoc.getElementsByTagName("result").item(0);
        		if (firstResult != null)
                {
        			zpid = firstResult.getElementsByTagName("zpid").item(0).getTextContent();
        			System.out.println("Zpid  "+zpid);
        
                }
        		Element yearbuilt = (Element)deepDoc.getElementsByTagName("yearBuilt").item(0);
        		if (yearbuilt != null)
        		{
        			yearbuiltT = yearbuilt.getTextContent(); 
        			System.out.println("Year Built  "+yearbuiltT);
        			info.add("Year Built  "+yearbuiltT);
        		}
        		Element lotsize = (Element)deepDoc.getElementsByTagName("lotSizeSqFt").item(0);
        		if (lotsize != null)
        		{
        			lotsizeT = lotsize.getTextContent(); 
        			System.out.println("Lot size  "+lotsizeT+" SqFt");
        			info.add("Lot size  "+lotsizeT+" SqFt");
        		}
        		Element bathrooms = (Element)deepDoc.getElementsByTagName("bathrooms").item(0);
        		if (bathrooms != null)
        		{
        			bathroomsT = bathrooms.getTextContent(); 
        			System.out.println("Bathrooms  "+bathroomsT);
        			info.add("Bathrooms  "+bathroomsT);
        		}
        		Element bedrooms = (Element)deepDoc.getElementsByTagName("bedrooms").item(0);
        		if (bedrooms != null)
        		{
        			bedroomsT = bedrooms.getTextContent(); 
        			System.out.println("Bedrooms  "+bedroomsT);
        			info.add("Bedrooms  "+bedroomsT);
        		}
        		Element lastsolddate = (Element)deepDoc.getElementsByTagName("lastSoldDate").item(0);
        		if (lastsolddate != null)
        		{
        			lastsolddateT = lastsolddate.getTextContent(); 
        			System.out.println("Last sold date  "+lastsolddateT);
        			info.add("Last sold date  "+lastsolddateT);
        		}
        		Element rentzestimate = (Element)deepDoc.getElementsByTagName("rentzestimate").item(0);
        		if (rentzestimate != null)
        		{
        			Element amount = (Element)rentzestimate.getElementsByTagName("amount").item(0);
        			if (amount != null)
        			{
        				amountT = amount.getTextContent();
        				currency_amt = amount.getAttribute("currency");
        			}
        			Element lastupdated = (Element)rentzestimate.getElementsByTagName("last-updated").item(0);
        			if (lastupdated != null)
        			{
        				lastupdatedT = lastupdated.getTextContent();
        			}
        			System.out.println("Average Price (updated "+lastupdatedT+") "+amountT+" "+currency_amt);
        			info.add("Average Price (updated "+lastupdatedT+") "+amountT+" "+currency_amt);
        			Element valuationRange = (Element)rentzestimate.getElementsByTagName("valuationRange").item(0);
        			if (valuationRange != null)
        			{
        				Element low = (Element)valuationRange.getElementsByTagName("low").item(0);
        				Element high = (Element)valuationRange.getElementsByTagName("high").item(0);
        				if ((low != null) && (high != null))
        				{	 
        					lowest = low.getTextContent();
        					currency_low = low.getAttribute("currency");
        					highest = high.getTextContent();
        					currency_high = amount.getAttribute("currency");
        					System.out.println("Price range "+lowest+" "+currency_low+" to "+highest+" "+currency_high);
        					info.add("Price range "+lowest+" "+currency_low+" to "+highest+" "+currency_high);
        				}
        			}
        		}
        		Element region = (Element)deepDoc.getElementsByTagName("region").item(0);
        		Element overview = (Element)deepDoc.getElementsByTagName("overview").item(0);
        		if ((region != null) && (overview != null))
        		{
        			reg_name = region.getAttribute("name");
        			overview_link = overview.getTextContent();
        			System.out.println("Real Estate  "+reg_name);
        			System.out.println("Overview  "+overview_link);
        			info.add("Real Estate  "+reg_name);
        			info.add("Overview  "+overview_link);
        		}
        		
				result = "Year Built: "+yearbuiltT+System.getProperty("line.separator")+ "Lot size: " +lotsizeT+" SqFt" + System.getProperty("line.separator") + "Number of Bathrooms: "+ bathroomsT +System.getProperty("line.separator")+"Number of Bedrooms:"+bedroomsT+System.getProperty("line.separator")+ "Last sold date:   "+lastsolddateT +System.getProperty("line.separator")+ "Average Rental Price (updated "+lastupdatedT+") "+amountT+" "+currency_amt +System.getProperty("line.separator")+ "Rental Price range "+lowest+" "+currency_low+" to "+highest+" "+currency_high + System.getProperty("line.separator") + "RealEstate: " + reg_name +System.getProperty("line.separator") +  "Overview: " + overview_link;
				//System.out.println(result);
        	}
        else 
        {
        	//System.out.println(statuscode.getElementsByTagName("text").item(0).getTextContent());
        	//result = statuscode.getElementsByTagName("text").item(0).getTextContent();
        	result = "Error: no exact match found for input address";
        	info.add(result);
        }
        
        //result = code;
        }
        System.out.println(result);
        return info;
    }
	 catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		info.add("Error: no exact match found for input address");
		return info;
    }
	
//	protected void onPostExecute(ArrayList<String> info) {
//		
//		
//    }
	
	
}
